'use client';

import React, { useState, useEffect, useRef, useMemo } from 'react';
import { createEditor, createToolbar, IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { message } from 'antd';
import { uploadFile } from '@/utils/file';
import { FileMetaType } from '@/types/file';
import '@wangeditor/editor/dist/css/style.css';

interface RichTextEditorProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  height?: number;
  disabled?: boolean;
}

const RichTextEditor: React.FC<RichTextEditorProps> = ({
  value = '',
  onChange,
  placeholder = '请输入文字',
  height = 200,
  disabled = false,
}) => {
  const editorRef = useRef<HTMLDivElement>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [toolbar, setToolbar] = useState<ReturnType<typeof createToolbar> | null>(null);
  const isInitialized = useRef(false);
  const editorId = useRef(`editor-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`);
  const initTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const toolbarConfig: Partial<IToolbarConfig> = useMemo(() => ({
    toolbarKeys: [
      'headerSelect',
      'bold',
      'italic',
      'underline',
      'through',
      'color',
      'bgColor',
      '|',
      'bulletedList',
      'numberedList',
      'todo',
      '|',
      'justifyLeft',
      'justifyCenter',
      'justifyRight',
      'justifyJustify',
      '|',
      'insertLink',
      'insertImage',
      'insertTable',
      '|',
      'undo',
      'redo',
      '|',
      'fullScreen'
    ]
  }), []);

  const editorConfig: Partial<IEditorConfig> = useMemo(() => ({
    placeholder,
    readOnly: disabled,
    autoFocus: false,
    EXTEND_CONF: {
      mentionConfig: {
        showModal: false,
        insertModal: false
      }
    },
    MENU_CONF: {
      uploadImage: {
        customUpload: async (file: File, insertFn: (url: string, alt?: string, href?: string) => void) => {
          try {
            const isImage = file.type.startsWith('image/');
            if (!isImage) {
              message.error('只能上传图片文件');
              return;
            }
            const maxSize = 10 * 1024 * 1024;
            if (file.size > maxSize) {
              message.error('图片大小不能超过10MB');
              return;
            }
            const result: FileMetaType = await uploadFile(file);
            const imageUrl = result.fileUrl || '';
            if (imageUrl) {
              insertFn(imageUrl, file.name, imageUrl);
              message.success('图片上传成功');
            } else {
              message.error('图片上传失败');
            }
          } catch (error) {
            console.error('图片上传失败:', error);
            message.error('图片上传失败，请重试');
          }
        },
        maxFileSize: 10 * 1024 * 1024,
        allowedFileTypes: ['image/*'],
        onBeforeUpload(file: File) {
          const isImage = file.type.startsWith('image/');
          if (!isImage) {
            message.error('只能上传图片文件');
            return false;
          }
          if (file.size > 10 * 1024 * 1024) {
            message.error('图片大小不能超过10MB');
            return false;
          }
          return true;
        }
      },
      insertLink: {
        checkLink: (_text: string, url: string) => {
          if (!url) {
            message.error('请输入链接地址');
            return false;
          }
          if (!url.startsWith('http://') && !url.startsWith('https://')) {
            message.error('请输入正确的链接地址');
            return false;
          }
          return true;
        }
      },
      insertTable: {
        maxRow: 20,
        maxCol: 10
      }
    }
  }), [placeholder, disabled]);

  // 初始化编辑器
  useEffect(() => {
    // 确保容器存在且编辑器未初始化
    if (isInitialized.current || !editorRef.current || !toolbarRef.current) {
      return;
    }

    // 清理之前的timeout
    if (initTimeoutRef.current) {
      clearTimeout(initTimeoutRef.current);
    }

    // 使用setTimeout来防抖，避免快速重复创建
    initTimeoutRef.current = setTimeout(() => {
      if (!editorRef.current || !toolbarRef.current || isInitialized.current) {
        return;
      }

      // 防止重复初始化
      let isMounted = true;
      isInitialized.current = true;
      console.log(`Creating editor with ID: ${editorId.current}`);

      // 清理可能存在的旧实例
      const existingEditor = editorRef.current.querySelector('.w-e-text-container');
      const existingToolbar = toolbarRef.current.querySelector('.w-e-toolbar');
      if (existingEditor) {
        console.log('Removing existing editor content');
        editorRef.current.innerHTML = '';
      }
      if (existingToolbar) {
        console.log('Removing existing toolbar content');
        toolbarRef.current.innerHTML = '';
      }

      try {
        const editorInstance = createEditor({
          selector: editorRef.current,
          html: value,
          config: editorConfig,
          mode: 'default'
        });

        const toolbarInstance = createToolbar({
          editor: editorInstance,
          selector: toolbarRef.current,
          config: toolbarConfig,
          mode: 'default'
        });

        // 只有在组件仍然挂载时才设置状态
        if (isMounted) {
          editorInstance.on('change', () => {
            const html = editorInstance.getHtml();
            onChange?.(html);
          });

          setEditor(editorInstance);
          setToolbar(toolbarInstance);
          console.log(`Editor created successfully with ID: ${editorId.current}`);
        } else {
          // 如果组件已卸载，立即清理
          editorInstance.destroy();
          toolbarInstance.destroy();
        }
      } catch (error) {
        console.error('Failed to create editor:', error);
        isInitialized.current = false;
      }
    }, 100); // 100ms防抖

    // 清理函数
    return () => {
      console.log(`Cleaning up editor with ID: ${editorId.current}`);

      // 清理timeout
      if (initTimeoutRef.current) {
        clearTimeout(initTimeoutRef.current);
        initTimeoutRef.current = null;
      }

      // 重置初始化标志
      isInitialized.current = false;
    };
  }, []); // 只在组件挂载时执行一次

  // 单独的清理effect，只在组件卸载时运行
  useEffect(() => {
    return () => {
      console.log('Component unmounting, destroying editor instances...');
      if (editor) {
        try {
          editor.destroy();
        } catch (error) {
          console.error('Error destroying editor:', error);
        }
      }
      if (toolbar) {
        try {
          toolbar.destroy();
        } catch (error) {
          console.error('Error destroying toolbar:', error);
        }
      }
    };
  }, []); // 空依赖数组，只在组件卸载时运行

  useEffect(() => {
    if (editor && value !== editor.getHtml()) {
      editor.setHtml(value);
    }
  }, [value, editor]);

  useEffect(() => {
    if (editor) {
      console.log('Updating editor disabled state:', disabled);
      if (disabled) {
        editor.disable();
      } else {
        editor.enable();
      }
    } else {
      console.log('Editor not initialized yet');
    }
  }, [disabled, editor]);

  return (
    <div style={{ 
      border: '1px solid #d9d9d9', 
      borderRadius: '6px',
      opacity: disabled ? 0.6 : 1,
    }}>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <div
          ref={toolbarRef}
          id={`${editorId.current}-toolbar`}
          style={{
            borderBottom: '1px solid #ccc',
            backgroundColor: '#fafafa'
          }}
        />
        <div
          ref={editorRef}
          id={`${editorId.current}-editor`}
          style={{
            height: height,
            overflowY: 'hidden',
            backgroundColor: '#fff'
          }}
        />
      </div>
      <style jsx global>{`
        .w-e-toolbar {
          border-bottom: 1px solid #e8e8e8 !important;
          background-color: #fafafa !important;
        }
        .w-e-text-container {
          background-color: #fff !important;
        }
        .w-e-text-container [data-slate-editor] {
          padding: 12px !important;
          line-height: 1.2 !important;
        }
        .w-e-text-container [data-slate-editor] p {
          margin: 2px !important;
        }
        .w-e-text-container [data-slate-editor] h1,
        .w-e-text-container [data-slate-editor] h2,
        .w-e-text-container [data-slate-editor] h3,
        .w-e-text-container [data-slate-editor] h4,
        .w-e-text-container [data-slate-editor] h5,
        .w-e-text-container [data-slate-editor] h6 {
          margin-top: 16px !important;
          margin-bottom: 8px !important;
          font-weight: 600 !important;
        }
        .w-e-text-container [data-slate-editor] ul,
        .w-e-text-container [data-slate-editor] ol {
          padding-left: 20px !important;
        }
        .w-e-text-container [data-slate-editor] table {
          border-collapse: collapse !important;
          width: 100% !important;
        }
        .w-e-text-container [data-slate-editor] table td,
        .w-e-text-container [data-slate-editor] table th {
          border: 1px solid #d9d9d9 !important;
          padding: 8px !important;
        }
        .w-e-text-container [data-slate-editor] blockquote {
          border-left: 4px solid #69cac3 !important;
          padding-left: 16px !important;
          margin: 16px 0 !important;
          color: #666 !important;
        }
        .w-e-text-container [data-slate-editor] code {
          background-color: #f5f5f5 !important;
          padding: 2px 4px !important;
          border-radius: 3px !important;
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
        }
        .w-e-text-container [data-slate-editor] img {
          max-width: 100% !important;
          height: auto !important;
          border-radius: 4px !important;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
        }
      `}</style>
    </div>
  );
};

export default React.memo(RichTextEditor);